package org.example.wikwok.service.impl;

import org.example.wikwok.common.ReturnedMessage;
import org.example.wikwok.mapper.*;
import org.example.wikwok.pojo.OperationLog;
import org.example.wikwok.pojo.Video;
import org.example.wikwok.pojo.VideoInfo;
import org.example.wikwok.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

//提供视频上传、删除、查看等逻辑。
@Service
public class VideoServiceImpl implements VideoService {
 @Autowired
 private VideoMapper videoMapper;
 @Autowired
 private LikeMapper likeMapper;
 @Autowired
 private CommentMapper commentMapper;
 @Autowired
 private Secondary_CommentMapper secondary_commentMapper;
 @Autowired
 private CollectMapper collectMapper;
 @Autowired
 private UserMapper userMapper;
 @Autowired
 private OperationLogMapper operationLogMapper;
 //视频上传

 @Override
 public int upload(Video video, int userId) {
  try {
   operationLogMapper.insert(OperationLog.build("User upload video ", userId, ReturnedMessage.VIDEOUPLOADEDSUCCESS));
   return videoMapper.insert(video);
  } catch (Exception e) {
   operationLogMapper.insert(OperationLog.build("User upload video ", userId, ReturnedMessage.VIDEOUPLOADFAILED));
   return -1;
  }
 }

 @Override
 public boolean delete(int videoId, int userId) {
  try {
   if (videoMapper.selectByPrimaryKey(videoId).getUploaderid() != userId) {
    operationLogMapper.insert(OperationLog.build("User delete video ", userId, ReturnedMessage.VIDEODELETEDFAILED));
    return false;
   }
   likeMapper.deleteByVideoId(videoId);
   secondary_commentMapper.deleteByVideoId(videoId);
   commentMapper.deleteByVideoId(videoId);
   collectMapper.deleteByVideoId(videoId);
   videoMapper.deleteByPrimaryKey(videoId);
   operationLogMapper.insert(OperationLog.build("User delete video ", userId, ReturnedMessage.VIDEODELETEDSUCCESS));
   return true;
  } catch (Exception e) {
   operationLogMapper.insert(OperationLog.build("User delete video ", userId, ReturnedMessage.VIDEODELETEDFAILED));
   return false;
  }
 }


 @Override
 public List<VideoInfo> list(int userId,int offset) {
  try {
   List<Video> videos = videoMapper.selectSome(offset);
   List<VideoInfo> videoInfoList = new ArrayList<>();
   for (Video video : videos) {
    videoInfoList.add(new VideoInfo(video, likeMapper.selectCountByVideoId(video.getId()), collectMapper.selectCountByVideoId(video.getId()), commentMapper.selectCountByVideoId(video.getId()) + secondary_commentMapper.selectByVideoId(video.getId()), userMapper.selectByPrimaryKey(video.getUploaderid())));
   }
   operationLogMapper.insert(OperationLog.build("User list video ", userId, ReturnedMessage.VIDEOLISTSUCCESS));
   return videoInfoList;
  } catch (Exception e) {
   operationLogMapper.insert(OperationLog.build("User list video ", userId, ReturnedMessage.VIDEOLISTFAILED));
   return null;
  }
 }
}
